"use client"
import React, { useEffect, useState } from "react"
import ReactECharts from "echarts-for-react"
import { getSignInRecord } from "@/api/user"
import { message } from "antd"
import dayjs from "dayjs"
import "./index.css"

/**
 * 刷题日历图
 */
const CalendarChart: React.FC = () => {
  // 签到日期列表（[1, 200]，表示第 1 和第 200 天有签到记录）
  const [dataList, setDataList] = useState<number[]>([])
  // 当前年份
  const year = new Date().getFullYear()

  const fetchDataList = async () => {
    try {
      const res = await getSignInRecord(year)
      setDataList(res.data)
    } catch (error) {
      if (error instanceof Error) {
        message.error("获取刷题记录失败，" + error.message)
      }
    }
  }

  useEffect(() => {
    fetchDataList()
  }, [])

  const optionsData = dataList.map((dayOfYear) => {
    const dataStr = dayjs(`${year}-01-01`)
      .add(dayOfYear - 1, "day")
      .format("YYYY-MM-DD")
    return [dataStr, 1]
  })

  // 图表配置
  const options = {
    visualMap: {
      show: false,
      min: 0,
      max: 1,
      inRange: {
        // 颜色从灰色到浅绿色
        color: ["#efefef", "lightgreen"]
      }
    },
    calendar: {
      range: year,
      left: 20,
      // 单元格自动宽度，高度为 16 像素
      cellSize: ["auto", 16],
      yearLabel: {
        position: "top",
        formatter: `${year} 年刷题记录`
      },
      monthLabel: { nameMap: "ZH" },
      dayLabel: { nameMap: "ZH" }
    },
    series: {
      type: "heatmap",
      coordinateSystem: "calendar",
      data: optionsData
    }
  }

  return <ReactECharts className="calendar-chart" option={options} />
}

export default CalendarChart
